<template>
  <view>
    <button @click="getLocation">获取位置</button>
    <view v-if="location">
      位置信息：{{ location.latitude }}, {{ location.longitude }}
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue';

const location = ref(null);

const getLocation = () => {
  wx.getLocation({
    type: 'wgs84',
    success(res) {
      location.value = {
        latitude: res.latitude,
        longitude: res.longitude,
        city: res.city,
        province: res.province,
        country: res.country,
      };
    },
    fail(err) {
      console.error('定位失败:', err);
      if (err.errMsg.indexOf('auth deny') > -1) {
        wx.showModal({
          title: '提示',
          content: '需要您的位置权限，请在设置中开启',
          showCancel: false,
          success: (res) => {
            if (res.confirm) {
              wx.openSetting({
                success(settingdata) {
                  if (settingdata.authSetting['scope.userLocation']) {
                    getLocation();
                  }
                },
              });
            }
          },
        });
      } else {
        wx.showToast({
          title: '定位失败，请稍后重试',
          icon: 'none',
        });
      }
    },
  });
};
</script>

<style scoped>
</style>